import time
import jwt
from django.contrib.auth.hashers import check_password,make_password
from take_out import settings
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.models import *
from myapp.serializer import *
from rest_framework.viewsets import ModelViewSet

# 检测用户登录的装饰器
def check_user(func):
    def check(cls,request):
        token = request.META.get('HTTP_TOKEN')
        try:
            payload = jwt.decode(token,settings.SECRET_KEY,algorithms='HS256')
            if payload['time'] < int(time.time()):
                return Response({'code':400,'msg':'token失败'})
        except Exception as e:
            return Response({'code':400,'msg':'验证失败'})
        return func(cls,request,payload)
    return check


# 登录
class Login(APIView):
    def post(self,request):
        username = request.data.get('name')
        pwd = request.data.get('password')
        try:
            try:
                user = User.objects.get(name=username)
            except:
                return Response({'code':400,'msg':'没有此用户 请先注册'})
            # 判断密码是否一致
            if pwd != user.password:
               return Response({'code':403,'msg':'密码错误'})

            payload = {'id':user.id,'name':user.name,'time':int(time.time())+6480000}
            token = jwt.encode(payload,settings.SECRET_KEY,algorithm='HS256')
            return Response({
                'code':200,'msg':'登录成功',
                'token':token
            })
        except Exception as e:
            return Response({"code":400,"msg":"登录失败"})


# 退出登录
class Logout(APIView):
    def post(self,request):
        return Response({'msg':'退出成功','code':200})


# 用户
# class UsersInfo(APIView):
#     @check_user
#     def get(self,request,paload):
#         user_id = paload['id']
#         user_info = User.objects.filter(id=user_id).first()  # 获取用户
#
#
#
#     def post(self):
#         pass


# 用户# 员工
class UserInfo(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'


    # 重写create方法
    def create(self,request,*args,**kwargs):
        name = request.data.get('name')
        sex = request.data.get('sex')
        info = request.data.get('info')
        auth = request.data.get('auth')
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        ident = request.data.get('ident')
        user = User.objects.filter(name=name,password=password).first()
        if user:
            return Response({'code':400,'msg':'商家已经存在'})
        ser = User.objects.create(name=name,sex=sex,info=info,auth=auth,mobile=mobile,password=password,ident=ident)
        ser.save()
        return Response({'code':200,'msg':'添加成功'})

    # def create(self, request, *args, **kwargs):
    #     try:
    #         User.objects.create(**request.data)
    #     except Exception as e:
    #         return Response({'code': 400, 'msg': '员工已经存在'})
    #     return Response({'code': 200, 'msg': '添加成功'})

    # 重写list方法

    # 重写update方法
    def update(self, request, *args, **kwargs):
        if not request.data.get('name'):
            name = User.objects.get(id=request.data['id']).name
            request.data['name']=name
            return super().update(request,*args,**kwargs)
        return super().update(request,*args,**kwargs)



# 地址
class UserAdder(APIView):
    @check_user
    def get(self,request,paLoad):
        user_id = request.data.get('id')
        print(user_id)
        # user_id = paLoad['id']
        user_info = User.objects.filter(id=user_id).first() # 获取用户
        if not user_info:
            return Response({'code':400,'msg':'用户不存在'})

        address_all = Address.objects.filter(user_id=user_info.id).all()

        address_list = []

        for addr in address_all:
            address = {
                'id':addr.id,
                'name':addr.addname,
                'longi':addr.longi,
                'mobile':addr.mobile,
                'username':addr.user.name
            }
            address_list.append(address)
        print(address_list)
        return Response({'code':200,'msg':'地址获取成功','data':address_list})

    @check_user
    def post(self,request,payload):
        user_id = payload['id']
        addname = request.data.get('addname')
        longi = request.data.get('longi')
        mobile = request.data.get('mobile')
        set_def = request.data.get('set_def')
        # user = request.data.get('user')
        Address.objects.create(addname=addname,longi=longi,mobile=mobile,set_def=set_def,user_id=user_id)

        return Response({'code':200,'msg':'新增地址成功'})


    @check_user
    def put(self,request,payload):
        user_id = payload['id'] # 获取用户id
        addr = Address.objects.filter(id=user_id).first()
        ser = AddrSerializer(instance=addr,data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code':200,'msg':'更新成功'})


    @check_user
    def delete(self,request, payload):
        id = request.data.get('id')
        Address.objects.filter(id=id).delete()
        return Response({'code':200,'msg':'删除成功'})





# 订单
class OrderInfo(ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    # todo 重写方法
    def update(self, request, *args, **kwargs):
        status = request.data.get('status')
        order = self.get_object()
        order.status = status
        order.save()
        return Response({"code":200,'msg':'更新订单成功'})


class OrderInfoView(APIView):
    @check_user
    def post(self,request,payload):
        user_id = payload['id']
        # 获取前端传来的数据
        remark = request.data.get('remark')  # 备注
        addre = request.data.get('addre.addname')  # 地址
        mercha = request.data.get('mercha.merch_name')  # 商家
        dishes = request.data.get('dishes.name')  # 菜品
        # todo 可能会出错！！！
        # 用户
        # user = User.objects.get(id=user_id).first()
        Order.objects.create(remark=remark,addre=addre,mercha=mercha,dishes=dishes)
        return Response({'code':200,'msg':'添加订单成功'})

    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        user_all = User.objects.get(id=user_id)

        order_list = []
        # 用户
        for user in user_all:
            a  = {
                'name':user.name,
                'mobile':user.mobile,
            }
        order_list.append(a)

        # 订单
        order_all = Order.objects.all()
        for order in order_all:
            b = {
                'number':order.number,
                'time':order.create_time,
                'address':order.addre.addname,
                'dishes':order.dishes.name,
                'merch' :order.mercha.merch_name
            }
            order_list.append(b)

            return Response({
                'code':200,'msg':'订单详情如下',
                'orderinfo':order_list
            })


# 菜品分类
class CommodityView(APIView):
    def get(self,request):
        commodity = Commodity.objects.all()
        if not commodity:
            return Response({'code':400,'msg':'没有商品'})
        commodity_list = []
        for i in commodity:
            a = {
                "comm_name":i.comm_name,
                "mercha":i.mercha.merch_name
            }
            commodity_list.append(a)
        return Response({"code":200,"msg":"获取成功",'data':commodity_list})

    def post(self,request):
        comm_name = request.data.get("comm_name")
        mercha = request.data.get("mercha")
        Commodity.objects.create(comm_name=comm_name,mercha_id=mercha)
        return Response({"code":200,"msg":"添加成功"})

class CommodityOneView(APIView):
    def get(self,request,pk):
        commodity = Commodity.objects.filter(id=pk).first()
        if not commodity:
            return Response({'code':400,'msg':'没有此商品'})
        ser = CommoditySer(commodity)
        return Response({"code":200,"msg":"获取成功","data":ser.data})

    def delete(self,request,pk):
        Commodity.objects.filter(id=pk).delete()
        return Response({"code":200,"msg":"删除成功"})

    def put(self,request,pk):
        commodity = Commodity.objects.filter(id=pk).first()
        ser = CommoditySer(instance=commodity,data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code': 200, 'msg': '更新成功'})



